﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Workflow.ComponentModel.Serialization;
using System.Workflow.ComponentModel;
using BPM.Foundation.WFDB;
using BPM.Base.Tools;
using System.IO;
using BPM.Base.WFLib;
using System.Web;

namespace BPM.Foundation.WFService
{
    public partial interface IWorkflowService
    {


    }
    public partial class WorkflowService : IWorkflowService
    {

        //[2.1	添加模版详细信息 （内部方法，不通过WCF公开）]
        private int? insertWFTemplate(WF_Template template, WFDBDataContext wfDB)
        {
            //[6]
            try
            {
                template.templateData = HttpUtility.HtmlDecode(template.templateData);
                System.Text.UTF8Encoding ut8 = new UTF8Encoding();
                byte[] bs = ut8.GetBytes(template.templateData);

                System.IO.MemoryStream ms = new MemoryStream(bs);

                XmlReader xmlReader = XmlReader.Create(ms);
                WorkflowMarkupSerializer serializer = new WorkflowMarkupSerializer();
                Activity activity = (Activity)serializer.Deserialize(xmlReader);
                updateActivityStruct(activity, template, wfDB);

            }
            catch (Exception ex)
            {
                MyLog.writeError(ex.Message);
                return 6;
            }

            return null;

        }

        //[2.2	保存工作流结构(内部方法)]
        private void updateActivityStruct(object activity, WF_Template template, WFDBDataContext wfDB)
        {

            if (activity is System.Workflow.ComponentModel.CompositeActivity)
            {
                System.Workflow.ComponentModel.CompositeActivity compositeActivity;
                compositeActivity = (System.Workflow.ComponentModel.CompositeActivity)activity;

                if (compositeActivity is BPM.Base.WFLib.状态机模板)
                {
                    状态机模板 stateTemplate = compositeActivity as BPM.Base.WFLib.状态机模板;

                    WF_TemplateInfo templateInfo = new WF_TemplateInfo();
                    templateInfo.ID = Guid.NewGuid();
                    templateInfo.powerID = stateTemplate.权限编号;
                    templateInfo.templateID = template.templateID;
                    templateInfo.templateEdition = template.templateEdition;
                    templateInfo.templateName = template.templateName;
                    templateInfo.templateDescription = template.templateDescription;
                    templateInfo.expandData = stateTemplate.扩展数据;
                    templateInfo.templateType = stateTemplate.模板类型;
                    templateInfo.startWindow = stateTemplate.启动窗体;
                    templateInfo.dataFormList = stateTemplate.数据表单列表;
                    templateInfo.startDataForm = stateTemplate.启动时填写的表单;
                    templateInfo.manageDepartment = stateTemplate.管理部门;
                    templateInfo.manageDuty = stateTemplate.管理职能;
                    templateInfo.manageUser = stateTemplate.管理人员;
                    templateInfo.seeDepartment = stateTemplate.查看部门;
                    templateInfo.seeDuty = stateTemplate.查看职能;
                    templateInfo.seeUser = stateTemplate.查看人员;
                    templateInfo.startUserPower = stateTemplate.启动人员特殊权限;
                    templateInfo.transactTimelimit = stateTemplate.办理时限;
                    templateInfo.overtimeOperate = stateTemplate.超时操作;

                    wfDB.WF_TemplateInfo.InsertOnSubmit(templateInfo);
                }
                else if (compositeActivity is BPM.Base.WFLib.顺序模板)
                {
                    顺序模板 stateTemplate = compositeActivity as BPM.Base.WFLib.顺序模板;

                    WF_TemplateInfo templateInfo = new WF_TemplateInfo();
                    templateInfo.ID = Guid.NewGuid();
                    templateInfo.powerID = stateTemplate.权限编号;
                    templateInfo.templateID = template.templateID;
                    templateInfo.templateEdition = template.templateEdition;
                    templateInfo.templateName = template.templateName;
                    templateInfo.templateDescription = template.templateDescription;
                    templateInfo.expandData = stateTemplate.扩展数据;
                    templateInfo.templateType = stateTemplate.模板类型;
                    templateInfo.startWindow = stateTemplate.启动窗体;
                    templateInfo.dataFormList = stateTemplate.数据表单列表;
                    templateInfo.startDataForm = stateTemplate.启动时填写的表单;
                    templateInfo.manageDepartment = stateTemplate.管理部门;
                    templateInfo.manageDuty = stateTemplate.管理职能;
                    templateInfo.manageUser = stateTemplate.管理人员;
                    templateInfo.seeDepartment = stateTemplate.查看部门;
                    templateInfo.seeDuty = stateTemplate.查看职能;
                    templateInfo.seeUser = stateTemplate.查看人员;
                    templateInfo.startUserPower = stateTemplate.启动人员特殊权限;
                    templateInfo.transactTimelimit = stateTemplate.办理时限;
                    templateInfo.overtimeOperate = stateTemplate.超时操作;

                    wfDB.WF_TemplateInfo.InsertOnSubmit(templateInfo);
                }

                foreach (object temp in compositeActivity.Activities)
                {
                    updateActivityStruct(temp, template, wfDB);
                }
            }
            else
            {
                if (activity is BPM.Base.WFLib.等待提交)
                {

                    等待提交 handleExternalEvent = activity as 等待提交;
                    WF_TemplateStateInfo templateStateInfo = new WF_TemplateStateInfo();
                    templateStateInfo.ID = Guid.NewGuid();
                    templateStateInfo.powerID = handleExternalEvent.权限编号;
                    templateStateInfo.templateID = template.templateID;
                    templateStateInfo.templateEdition = template.templateEdition;
                    templateStateInfo.stateID = handleExternalEvent.状态编号;
                    templateStateInfo.stateName = handleExternalEvent.状态名称;
                    templateStateInfo.stateDescription = handleExternalEvent.状态说明;
                    templateStateInfo.transactType = handleExternalEvent.处理方式;
                    templateStateInfo.expandData = handleExternalEvent.扩展数据;
                    templateStateInfo.startWindow = handleExternalEvent.启动窗体;
                    templateStateInfo.dataFormType = handleExternalEvent.数据表单类型;
                    templateStateInfo.dataExpression = handleExternalEvent.数据分流表达式;
                    templateStateInfo.transactUser = handleExternalEvent.办理人员;
                    templateStateInfo.transactPower = handleExternalEvent.办理时特殊权限;
                    templateStateInfo.transactTimelimit = handleExternalEvent.办理时限;
                    templateStateInfo.transactOvertimeOperate = handleExternalEvent.办理超时操作;
                    templateStateInfo.transactOption = handleExternalEvent.办理提交选项;
                    templateStateInfo.transactSeeForm = handleExternalEvent.办理查看业务表单;
                    templateStateInfo.transactWriteForm = handleExternalEvent.办理添写业务表单;
                    templateStateInfo.inceptDepartment = handleExternalEvent.接件部门;
                    templateStateInfo.inceptDuty = handleExternalEvent.接件职能;
                    templateStateInfo.inceptPower = handleExternalEvent.接件时特殊权限;
                    templateStateInfo.inceptTimelimit = handleExternalEvent.接件时限;
                    templateStateInfo.inceptOvertimeOperate = handleExternalEvent.接件超时操作;
                    templateStateInfo.assignDepartment = handleExternalEvent.分配部门;
                    templateStateInfo.assignDuty = handleExternalEvent.分配职能;
                    templateStateInfo.assignUser = handleExternalEvent.分配人员;
                    templateStateInfo.assignPower = handleExternalEvent.分配时特殊权限;
                    templateStateInfo.assignTimelimit = handleExternalEvent.分配时限;
                    templateStateInfo.assignOvertimeOperate = handleExternalEvent.分配超时操作;
                    templateStateInfo.manageDepartment = handleExternalEvent.管理部门;
                    templateStateInfo.manageDuty = handleExternalEvent.管理职能;
                    templateStateInfo.manageUser = handleExternalEvent.管理人员;
                    templateStateInfo.managePower = handleExternalEvent.管理时特殊权限;
                    templateStateInfo.seeDepartment = handleExternalEvent.查看部门;
                    templateStateInfo.seeDuty = handleExternalEvent.查看职能;
                    templateStateInfo.seeUser = handleExternalEvent.查看人员;
                    templateStateInfo.seePower = handleExternalEvent.查看时特殊权限;
                    templateStateInfo.dynamicDepartment = handleExternalEvent.动态域部门;
                    templateStateInfo.dynamicDuty = handleExternalEvent.动态域职能;
                    templateStateInfo.dynamicUser = handleExternalEvent.动态域人员;
                    templateStateInfo.dynamicPower = handleExternalEvent.动态域特殊权限;
                    templateStateInfo.dynamicTimelimit = handleExternalEvent.分配时限;
                    templateStateInfo.dynamicType = handleExternalEvent.动态域类型;

                    wfDB.WF_TemplateStateInfo.InsertOnSubmit(templateStateInfo);

                }
            }

        }

      
        //[2.3 删除XOML的Class头 （内部方法，不通过WCF公开）]
        private void deleteClassAttributeOfXoml(WF_Template template)
        {
            string xoml = template.templateData;
            int start, end1, end2;
            start = xoml.IndexOf("x:Class");
            if (start < 0)
            {
                return;
            }
            end1 = xoml.IndexOf("\"", start);
            if (end1 < 0)
            {
                return;
            }
            end2 = xoml.IndexOf("\"", end1 + 1);
            if (end2 < 0)
            {
                return;
            }

            template.templateData = xoml.Replace(xoml.Substring(start, end2 - start + 1), "");

        }

        //[2.4	添加工作流模版]
        public int? insertWFTemplate(string pid, WF_Template template)
        {
            using (WFDBDataContext wfDB = new WFDBDataContext(MyConfig.getConnection("myconstring")))
            {
                //[1]
                if (template == null)
                {
                    return 1;
                }

                //[2]
                if (string.IsNullOrEmpty(template.templateID))
                {
                    return 2;
                }

                //[3]
                if (string.IsNullOrEmpty(template.templateEdition))
                {
                    return 3;
                }

                //[5]
                if (String.IsNullOrEmpty(template.templateData))
                {
                    return 5;
                }

                //-
                deleteClassAttributeOfXoml(template);

                //-
                if (wfDB.WF_Template.Count(p => p.templateID == template.templateID && p.templateEdition == template.templateEdition) == 1)
                {
                    return 7;
                }

                //[调用3]
                var succeed = insertWFTemplate(template, wfDB);
                if (succeed != null)
                {
                    return succeed;
                }
                //-
                template.ID = Guid.NewGuid();

                //[4]
                wfDB.WF_Template.InsertOnSubmit(template);
                try
                {
                    wfDB.SubmitChanges();
                    return null;
                }
                catch (Exception ex)
                {
                    MyLog.writeError(ex.Message);
                    return 4;
                }
            }
        }

        //[2.5	得到工作流模版]
        public WF_Template getWFTemplate(string pid, string templateID, string templateEdition)
        {
            using (WFDBDataContext wfDB = new WFDBDataContext(MyConfig.getConnection("myconstring")))
            {
                //[1]
                if (string.IsNullOrEmpty(templateID))
                {
                    return null;
                }

                //[2]
                if (string.IsNullOrEmpty(templateEdition))
                {
                    return null;
                }

                //[3]
                if (wfDB.WF_Template.Count(p => p.templateID == templateID && p.templateEdition == templateEdition) == 1)
                {
                    WF_Template template = wfDB.WF_Template.Single(p => p.templateID == templateID && p.templateEdition == templateEdition);
                    return template;
                }
                else
                {
                    return null;
                }
            }
        }

        //[2.6	得到工作流结构]
        public WF_Structure getWFStructure(string pid, string templateID, string templateEdition)
        {
            using (WFDBDataContext wfDB = new WFDBDataContext(MyConfig.getConnection("myconstring")))
            {
                //[1]
                if (string.IsNullOrEmpty(templateID))
                {
                    return null;
                }

                //[2]
                if (string.IsNullOrEmpty(templateEdition))
                {
                    return null;
                }

                WF_Structure structure = new WF_Structure();

                var templateV = wfDB.WF_Template_V.SingleOrDefault(p => p.templateID == templateID && p.templateEdition == templateEdition);
                structure.wfTemplateV = templateV;

                try
                {
                    var templateStateInfo = wfDB.WF_TemplateStateInfo.Where(p => p.templateID == templateID && p.templateEdition == templateEdition);
                    structure.wfTemplateStateInfo = templateStateInfo.ToList();
                }
                catch (Exception ex)
                {
                    MyLog.writeError(ex.Message);
                }

                var templateInfo = wfDB.WF_TemplateInfo.SingleOrDefault(p => p.templateID == templateID && p.templateEdition == templateEdition);
                structure.wfTemplateInfo = templateInfo;

                return structure;
            }

        }

        //[2.7	得到工作流模版列表]
        public List<WF_Template_V> searchWFTemplate(string pid, string templateID, string templateEdition)
        {

            using (WFDBDataContext wfDB = new WFDBDataContext(MyConfig.getConnection("myconstring")))
            {
                //[1]
                if (string.IsNullOrEmpty(templateID) && string.IsNullOrEmpty(templateEdition))
                {
                    var templateList = wfDB.WF_Template_V.ToList();
                    return templateList;
                }

                //[2]
                if (!string.IsNullOrEmpty(templateID) && string.IsNullOrEmpty(templateEdition))
                {
                    var template = wfDB.WF_Template_V.Where(p => p.templateID == templateID);
                    return template.ToList();
                }

                //[3]
                if (string.IsNullOrEmpty(templateID) && !string.IsNullOrEmpty(templateEdition))
                {
                    var template = wfDB.WF_Template_V.Where(p => p.templateEdition == templateEdition);
                    return template.ToList();
                }

                //[4]
                if (!string.IsNullOrEmpty(templateID) && !string.IsNullOrEmpty(templateEdition))
                {
                    var template = wfDB.WF_Template_V.Where(p => p.templateID == templateID && p.templateEdition == templateEdition);
                    return template.ToList();
                }
                else
                {
                    return null;
                }
            }
        }

        //[2.8	删除工作流模版]
        public int? deleteWFTemplate(string pid, string templateID, string templateEdition)
        {
            using (WFDBDataContext wfDB = new WFDBDataContext(MyConfig.getConnection("myconstring")))
            {
                //[1]
                if (string.IsNullOrEmpty(templateID))
                {
                    return 1;
                }

                //[2]
                if (string.IsNullOrEmpty(templateEdition))
                {
                    return 2;
                }

                //[3]
                if (wfDB.WF_Template.Count(p => p.templateID == templateID && p.templateEdition == templateEdition) == 0)
                {
                    return 3;
                }

                //[4]
                if (wfDB.WF_Template.Count(p => p.templateID == templateID && p.templateEdition == templateEdition) == 1)
                {
                    var template = wfDB.WF_Template.Single(p => p.templateID == templateID && p.templateEdition == templateEdition);
                    wfDB.WF_Template.DeleteOnSubmit(template);
                    try
                    {
                        wfDB.SubmitChanges();
                    }
                    catch (System.Exception ex)
                    {
                        MyLog.writeError(ex.Message);
                    }
                    return null;
                }
                else
                {
                    return -1;
                }
            }
        }

        //[2.9	添加启动流程权限]
        public int? addStartWorkflowPower(string pid, WF_StartWorkflowPower wf_StartWorkflowPower)
        {
            using (WFDBDataContext wfDB = new WFDBDataContext(MyConfig.getConnection("myconstring")))
            {
                //[1]
                if (wf_StartWorkflowPower == null)
                {
                    return 1;
                }

                //[2]
                if (wfDB.WF_Template.Count(p => p.templateID == wf_StartWorkflowPower.templateID
                                                                && p.templateEdition == wf_StartWorkflowPower.templateEdition) != 1)
                {
                    return 2;
                }
                //[3,4]
                //if (wf_StartWorkflowPower.userNo == "all")
                //{
                //    if (wfDB.PW_DutyInDepartment_V.Count(p => p.dutyNo == wf_StartWorkflowPower.dutyNo
                //                                                        && p.departmentNo == wf_StartWorkflowPower.departmentNo) != 1)
                //    {
                //        return 3;
                //    }
                //}
                //else
                //{
                //    if (wfDB.PW_DepartmentDutyUserRelation_V.Count(p => p.userNo == wf_StartWorkflowPower.userNo
                //                                                        && p.dutyNo == wf_StartWorkflowPower.dutyNo
                //                                                        && p.departmentNo == wf_StartWorkflowPower.departmentNo) != 1)
                //    {
                //        return 4;
                //    }
                //}
                //[5]
                if (wfDB.WF_StartWorkflowPower.Count(p => p.userNo == wf_StartWorkflowPower.userNo
                                                            && p.dutyNo == wf_StartWorkflowPower.dutyNo
                                                            && p.departmentNo == wf_StartWorkflowPower.departmentNo
                                                            && p.templateEdition == wf_StartWorkflowPower.templateEdition
                                                            && p.templateID == wf_StartWorkflowPower.templateID) != 0)
                {
                    return 5;
                }

                //[6]
                wf_StartWorkflowPower.ID = Guid.NewGuid();
                wfDB.WF_StartWorkflowPower.InsertOnSubmit(wf_StartWorkflowPower);
                try
                {
                    wfDB.SubmitChanges();
                }
                catch (System.Exception ex)
                {
                    MyLog.writeError(ex.Message);
                }
                return null;
            }
        }

        //[2.10	移除启动流程权限]
        public int? removeStartWorkflowPower(string pid, WF_StartWorkflowPower wf_StartWorkflowPower)
        {
            using (WFDBDataContext wfDB = new WFDBDataContext(MyConfig.getConnection("myconstring")))
            {
                //[1]
                if (wf_StartWorkflowPower == null)
                {
                    return 1;
                }

                //[2]
                WF_StartWorkflowPower wf_StartWorkflowPowerFromDB =
                    wfDB.WF_StartWorkflowPower.SingleOrDefault(p => p.userNo == wf_StartWorkflowPower.userNo
                                                            && p.dutyNo == wf_StartWorkflowPower.dutyNo
                                                            && p.departmentNo == wf_StartWorkflowPower.departmentNo
                                                            && p.templateEdition == wf_StartWorkflowPower.templateEdition
                                                            && p.templateID == wf_StartWorkflowPower.templateID);

                if (wf_StartWorkflowPowerFromDB == null)
                {
                    return 2;
                }
                else
                {
                    //[3]
                    wfDB.WF_StartWorkflowPower.DeleteOnSubmit(wf_StartWorkflowPowerFromDB);
                    try
                    {
                        wfDB.SubmitChanges();
                    }
                    catch (System.Exception ex)
                    {
                        MyLog.writeError(ex.Message);
                    }
                    return null;
                }
            }
        }

        //[2.11	得到启动流程权限列表]
        public List<WF_StartWorkflowPower_V> getStartWorkflowPower(string pid, string userNo, string departmentNo, string dutyNo)
        {
            using (WFDBDataContext wfDB = new WFDBDataContext(MyConfig.getConnection("myconstring")))
            {
                //[1]
                if (string.IsNullOrEmpty(departmentNo) && string.IsNullOrEmpty(dutyNo) && string.IsNullOrEmpty(userNo))
                {
                    return wfDB.WF_StartWorkflowPower_V.ToList();
                }
                //[2]
                if ((!string.IsNullOrEmpty(departmentNo)) && string.IsNullOrEmpty(dutyNo) && string.IsNullOrEmpty(userNo))
                {
                    return wfDB.WF_StartWorkflowPower_V.Where(p => p.departmentNo == departmentNo).ToList();
                }
                //[3]
                if (string.IsNullOrEmpty(departmentNo) && (!string.IsNullOrEmpty(dutyNo)) && string.IsNullOrEmpty(userNo))
                {
                    return wfDB.WF_StartWorkflowPower_V.Where(p => p.dutyNo == dutyNo).ToList();
                }

                //[4]
                if (string.IsNullOrEmpty(departmentNo) && (string.IsNullOrEmpty(dutyNo)) && (!string.IsNullOrEmpty(userNo)))
                {
                    return wfDB.WF_StartWorkflowPower_V.Where(p => p.userNo == userNo).ToList();
                }

                //[5]
                if ((!string.IsNullOrEmpty(departmentNo)) && (!string.IsNullOrEmpty(dutyNo)) && string.IsNullOrEmpty(userNo))
                {
                    return wfDB.WF_StartWorkflowPower_V.Where(p => p.departmentNo == departmentNo && p.dutyNo == dutyNo).ToList();
                }
                //[6]
                if ((!string.IsNullOrEmpty(departmentNo)) && (!string.IsNullOrEmpty(dutyNo)) && (!string.IsNullOrEmpty(userNo)))
                {
                    return wfDB.WF_StartWorkflowPower_V.Where(p => p.userNo == userNo && p.departmentNo == departmentNo && p.dutyNo == dutyNo).ToList();
                }

                return wfDB.WF_StartWorkflowPower_V.Where(p => false).ToList();
            }
        }

        //[2.12	删除工作流模版信息]
        public int? deleteWFTemplateInfo(string pid, string templateID, string templateEdition)
        {
            using (WFDBDataContext wfDB = new WFDBDataContext(MyConfig.getConnection("myconstring")))
            {
                //[1]
                if (string.IsNullOrEmpty(templateID))
                {
                    return 1;
                }

                //[2]
                if (string.IsNullOrEmpty(templateEdition))
                {
                    return 2;
                }

                //[3]
                if (wfDB.WF_TemplateInfo.Count(p => p.templateID == templateID && p.templateEdition == templateEdition) == 0)
                {
                    return 3;
                }

                //[4]
                if (wfDB.WF_TemplateInfo.Count(p => p.templateID == templateID && p.templateEdition == templateEdition) == 1)
                {
                    var template = wfDB.WF_TemplateInfo.Single(p => p.templateID == templateID && p.templateEdition == templateEdition);
                    wfDB.WF_TemplateInfo.DeleteOnSubmit(template);
                    try
                    {
                        wfDB.SubmitChanges();
                    }
                    catch (System.Exception ex)
                    {
                        MyLog.writeError(ex.Message);
                    }
                    return null;
                }
                else
                {
                    return -1;
                }
            }
        }


        //[2.13 得到工作流模板的启动流程权限列表]
        public List<WF_StartWorkflowPower_V> getWFTemplateStartWorkflowPower(string pid, string templateId, string templateEdition)
        {
            using (WFDBDataContext wfDB = new WFDBDataContext(MyConfig.getConnection("myconstring")))
            {
                //[1]
                if (string.IsNullOrEmpty(templateId) && string.IsNullOrEmpty(templateEdition))
                {
                    return wfDB.WF_StartWorkflowPower_V.ToList();
                }
                //--

                //[2]
                if (string.IsNullOrEmpty(templateId))
                {
                    return wfDB.WF_StartWorkflowPower_V.Where(p => p.templateEdition == templateEdition).ToList();
                }
                //-

                //[3]
                if (string.IsNullOrEmpty(templateEdition))
                {
                    return wfDB.WF_StartWorkflowPower_V.Where(p => p.templateID == templateId).ToList();
                }
                //--

                //[4]
                return wfDB.WF_StartWorkflowPower_V.Where(p =>
                    p.templateID == templateId &&
                    p.templateEdition == templateEdition).ToList();
                //-
            }
        }
        //--

    
    }
}
